package tcc.tests;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;

import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SocketClientActivity extends Activity {
	private Socket mSocket = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    public void connectAction(View view) {
    	Context ctx = getApplicationContext();
    	
    	EditText etIp = (EditText) findViewById(R.id.editText_connectionIP);
    	EditText etPort = (EditText) findViewById(R.id.editText_connectionPort);
    	
    	try {
	    	String ip = etIp.getText().toString();
	    	int port = Integer.parseInt(etPort.getText().toString());
    		mSocket = new Socket(ip, port);
        	Toast.makeText(ctx, "Connected", Toast.LENGTH_SHORT).show();
		} catch (UnknownHostException e) {
        	Toast.makeText(ctx, "Unknown Host", Toast.LENGTH_SHORT).show();
		} catch (IOException e) {
        	Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
        	Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_SHORT).show();
		}
    }
    
    public void sendAction(View view) {
    	Context ctx = getApplicationContext();
    	if (mSocket == null) {
    		Toast.makeText(ctx, "Connect before sending", Toast.LENGTH_SHORT).show();
    	} else {
	    	TextView etInput = (TextView)findViewById(R.id.editText_inputMessage);
	    	TextView etOutput = (TextView)findViewById(R.id.editText_outputMessage);
	    	
	    	try {
				PrintWriter out = new PrintWriter(mSocket.getOutputStream(), true);
				
				String input = etInput.getText().toString();
				out.println(input);
				out.flush();
	
				BufferedReader in = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
	
				boolean waitingForOutput = true;
				String newOutput = etOutput.getText().toString();
				do {
					String output;
					while ((output = in.readLine()) != null) {
						waitingForOutput = false;
						newOutput = newOutput + output;
					}
					etOutput.setText(newOutput);
				} while (waitingForOutput);
			} catch (Exception e) {
	        	Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_SHORT).show();
			}
			
			try {
				mSocket.close();
				mSocket = null;
			} catch (Exception e) {
				Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_SHORT).show();
			}
    	}
    }
    
    public void clearAction(View view) {
    	TextView etOutput = (TextView)findViewById(R.id.editText_outputMessage);
    	etOutput.setText("");
    }
    
    
}